package com.kung.qvs.ui.main;

import android.app.Application;
import android.os.Handler;
import android.os.Looper;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.kung.qvs.data.JtRepository;
import com.kung.qvs.entity.DeviceBean;
import com.kung.qvs.entity.PrintDataBean;
import com.kung.qvs.entity.PropInfoBean;
import com.kung.qvs.entity.ReqUpdateStateBean;
import com.kung.qvs.entity.database.SqlManager;
import com.kung.qvs.utils.Constants;
import com.kung.qvs.utils.DateUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.BaseResponseBean;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

public class HomeViewModel extends BaseViewModel<JtRepository> {
    public HomeViewModel(@NonNull Application application, JtRepository model) {
        super(application, model);
    }

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();
    public class UIChangeObservable {
        public SingleLiveEvent eventStopTimerCommond = new SingleLiveEvent();   //停止上传任务
        public SingleLiveEvent eventNoticeFinishUpload = new SingleLiveEvent();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        try {
            //删除当天前的本地垃圾记录
            SqlManager.deletePrintDataBeans(model.getEquipmentNo(), DateUtils.getCurrentDateTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        // TODO: 2022/8/18 0018  需要设置设备编号
//        model.saveEquipmentNo("DZC00001");
    }

    public void deleteBtDeviceWeigh(String type) {
        SqlManager.deleteDeviceBeanByType(type, model.getAccount());
    }
    public String getBtMacWeigh(String type) {
        return SqlManager.queryDeviceBeanMacByType(type, model.getAccount());
    }
    public String getBtNameWeigh(String type) {
        return SqlManager.queryDeviceBeanNameByType(type, model.getAccount());
    }
    public void saveBtMacWeigh(String mac, String name) {
        DeviceBean deviceBean = new DeviceBean();
        deviceBean.set_id(null);
        deviceBean.setFaccount(model.getAccount());
        deviceBean.setFdeviceType(Constants.DEVICE_TYPE1);
        deviceBean.setFdevicesMac(mac);
        deviceBean.setFdevicesName(name);
        SqlManager.insertOrReplaceDeviceBean(deviceBean);
    }

    public void saveBtMacPrint(String mac, String name) {
        DeviceBean deviceBean = new DeviceBean();
        deviceBean.set_id(null);
        deviceBean.setFaccount(model.getAccount());
        deviceBean.setFdeviceType(Constants.DEVICE_TYPE2);
        deviceBean.setFdevicesMac(mac);
        deviceBean.setFdevicesName(name);
        SqlManager.insertOrReplaceDeviceBean(deviceBean);
    }

    public void setHardWareCode(String hardwareCode) {
        model.saveEquipmentNo(hardwareCode);
        doGetPropInfo(model.getEquipmentNo());
    }
    public String getEquipmentNo(){
        return model.getEquipmentNo();
    }

    //生成设备信息
    public void doAddDevice(String serialNo) {

    }

    public void doUpdateStatus() {
        if (StringUtils.isTrimEmpty(model.getEquipmentNo())) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Looper.prepare();
                    ToastUtils.showShort("没有获取到设备编号");
                    Looper.loop();//增加部分
                }
            }).start();

            return;
        }

        ReqUpdateStateBean reqBean = new ReqUpdateStateBean();
        reqBean.setHardwareCode(model.getEquipmentNo());
        long time = new Date().getTime();
        reqBean.setTimestamp(time + "");
        Gson gson = new Gson();
        String route = gson.toJson(reqBean);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; Accept: application/json"), route);


    }

    /**
     * 上传垃圾记录
     */
    public void doAddWasReport() {
        if (StringUtils.isTrimEmpty(model.getEquipmentNo())) {
            return;
        }
        //获取垃圾记录
        List<PrintDataBean> trashDataBeans = SqlManager.getPrintDataBeanList(model.getEquipmentNo(), "1");
        if(trashDataBeans == null || trashDataBeans.size() == 0) {
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    uc.eventStopTimerCommond.call();
                }
            });
            return;
        }
        PrintDataBean reqBean = trashDataBeans.get(0);
//        model.doSetPrintCertificate(reqBean.getEquipmentNo(),
//                reqBean.getPrintCode(),
//                reqBean.getPromise(),
//                reqBean.getBasis(),
//                reqBean.getProductClassId(),
//                reqBean.getProductId(),
//                reqBean.getIssueDate(),
//                reqBean.getWeight(),
//                reqBean.getOriginPlace(),
//                reqBean.getProducer(),
//                reqBean.getContact()).compose(RxUtils.schedulersTransformer()) //线程调度
//                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
//                .doOnSubscribe(this)//请求与ViewModel周期同步
//                .doOnSubscribe(new Consumer<Disposable>() {
//                    @Override
//                    public void accept(Disposable disposable) throws Exception {
////                        showDialog("正在请求数据...");
//                    }
//                })
//                .subscribe(new DisposableObserver<BaseResponseBean>() {
//                    @Override
//                    public void onNext(BaseResponseBean response) {
//                        //请求成功
//                        if (response.isOk()) {
//                            //数据插入本地，并根据id排序查询。已被无网络情况使用
//                            //更新状态
//                            reqBean.setFst("3");
//                            SqlManager.updatePrintDataBean(reqBean);    //暂不删除，改为更新
//                        } else {
//                            //code错误时也可以定义Observable回调到View层去处理
////                            ToastUtils.showShort(response.getMessage());
//                        }
//                    }
//
//                    @Override
//                    public void onError(Throwable throwable) {
//                        //关闭对话框
////                        dismissDialog();
//                        if (throwable instanceof ResponseThrowable) {
//                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
//
//                        }
//                    }
//
//                    @Override
//                    public void onComplete() {
//                        //关闭对话框
//                        dismissDialog();
//                    }
//                });
    }

    //企业信息下载
    public void doGetPropInfo(String equipmentNo) {

//        model.doGetPropInfo(equipmentNo).compose(RxUtils.schedulersTransformer()) //线程调度
//                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
//                .doOnSubscribe(this)//请求与ViewModel周期同步
//                .doOnSubscribe(new Consumer<Disposable>() {
//                    @Override
//                    public void accept(Disposable disposable) throws Exception {
////                        showDialog("正在请求数据...");
//                    }
//                })
//                .subscribe(new DisposableObserver<BaseResponseBean<PropInfoBean>>() {
//                    @Override
//                    public void onNext(BaseResponseBean<PropInfoBean> response) {
//                        //请求成功
//                        if (response.isOk()) {
//                            PropInfoBean bean = response.getData();
//                            bean.set_id(null);
//                            bean.setLocalId(Constants.LOCAL_CODE_DEFAULT);
//                            SqlManager.insertOrReplacePropInfoBean(bean);
//                        } else {
////                            ToastUtils.showShort(response.getMessage());
//                        }
//                    }
//
//                    @Override
//                    public void onError(Throwable throwable) {
//                        //关闭对话框
////                        dismissDialog();
//                        if (throwable instanceof ResponseThrowable) {
//                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
//                        }
//                    }
//
//                    @Override
//                    public void onComplete() {
//                        //关闭对话框
//                        dismissDialog();
//                    }
//                });
    }
}
